package com.yanqu.road.server.manager.activity.suitang.manager;

import com.yanqu.road.entity.activity.suitang.config.SuiTangCityTypeConfig;
import com.yanqu.road.entity.activity.suitang.data.CrossSuiTangUnionData;
import com.yanqu.road.entity.activity.suitang.data.CrossSuiTangUnionJoinData;
import com.yanqu.road.entity.activity.suitang.data.CrossSuiTangUserData;
import com.yanqu.road.entity.activity.suitang.data.CrossSuiTangCity;
import com.yanqu.road.entity.activity.suitang.entity.rank.CrossSuiTangRank;
import com.yanqu.road.entity.activity.suitang.entity.rank.CrossSuiTangRankListModel;
import com.yanqu.road.entity.activity.suitang.entity.team.CrossSuiTangTeam;
import com.yanqu.road.entity.activity.suitang.entity.union.CrossSuiTangUnionJoinMember;
import com.yanqu.road.entity.activity.suitang.entity.union.CrossSuiTangUnionRound;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangCityType;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangWarType;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangStage;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.rank.yrank.UnionYRank;
import com.yanqu.road.entity.rank.yrank.UserYRank;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manager.yrank.CrossYRankMgr;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossSuiTangRankActivityMgr extends CrossBaseActivityMgr {

    protected static Logger logger = LogManager.getLogger(CrossSuiTangRankActivityMgr.class.getName());
    /*
     * 更新城池战场内玩家的军功排行
     */
    public void updateWarUserRank(int cityId, long userId, long zhanGong, long cost, long time) {
        CrossSuiTangUserData user = activity.getUserData(userId);
        CrossSuiTangCity city = getCurCity(userId, cityId);
        CrossSuiTangRankListModel cityRank = getCityRank(city, user.getUnionUid());
        if (cityRank != null) {
            CrossSuiTangRank myRankInfo = cityRank.getMyRankInfo(String.valueOf(userId));
            long totalZhanGong = myRankInfo == null ? zhanGong : myRankInfo.getValue() + zhanGong;
            long totalCost = myRankInfo == null ? cost : myRankInfo.getAbility() + cost;
            cityRank.rankChange(new CrossSuiTangRank(String.valueOf(userId), totalZhanGong, totalCost, time));
        }
    }

    /*
     * 更新个人军功排行
     */
    public void updateUserRank(long userId, long zhanGong, long time) {
        CrossSuiTangUserData userData = activity.getUserData(userId);
        CrossSuiTangUnionJoinMember unionJoinMember = getUnionJoinMember(userData.getUnionUid(), userId);
//        CrossSuiTangRankListModel cityRank = getUserRank();
//        if (cityRank != null) {
//            cityRank.rankChange(new CrossSuiTangRank(String.valueOf(userId), zhanGong, ability, time));
//        }
        UserYRank userYRank = new UserYRank();
        userYRank.setUserId(userId);
        userYRank.setActivityId(activity.getConfig().getActivityId());
        userYRank.setGroupId(activity.getGroupId());
        userYRank.setIdKey(String.valueOf(eGamePlayerEventType.SuiTangUserZhanGongRank.getValue()));
        userYRank.setValue(BigInteger.valueOf(zhanGong));
        userYRank.setUpdateTime(time);
        userYRank.setUserBaseInfo(CrossUserMgr.getUserBaseInfo(userId));
        CrossYRankMgr.userRankChange(userYRank);
    }

    /*
     * 更新商会积分排行
     */
    public void updateUnionRank(String unionId, long score, long time) {
        CrossSuiTangUnionJoinData unionJoin = getUnionJoin(unionId);
        // v6.9 改为赚钱
        long ability = unionJoin == null ? 0 : unionJoin.getUnionBaseInfo().getTotalPatronsAbility().longValue();
//        CrossSuiTangRankListModel cityRank = getUnionRank();
//        if (cityRank != null) {
//            CrossSuiTangRank myRankInfo = cityRank.getMyRankInfo(unionId);
//            long scoreTemp = myRankInfo == null ? score : Math.max(myRankInfo.getValue() + score, 0);
//            cityRank.rankChange(new CrossSuiTangRank(unionId, scoreTemp, ability, time));
//        }
        int warType = 0;
        CrossSuiTangUnionRound unionRoundData = getUnionRoundData(unionId);
        if (unionRoundData != null) {
            warType = unionRoundData.getWarType().getType();
        }
        UnionYRank unionYRank = CrossYRankMgr.getUnionYRank(activity.getConfig().getActivityId(), activity.getGroupId(), String.valueOf(eGamePlayerEventType.SuiTangUnionScoreRank.getValue()), unionId);
        if (unionYRank == null) {
            unionYRank = new UnionYRank();
        }
        unionYRank.setUnionUid(unionId);
        unionYRank.setActivityId(activity.getConfig().getActivityId());
        unionYRank.setGroupId(activity.getGroupId());
        unionYRank.setIdKey(String.valueOf(eGamePlayerEventType.SuiTangUnionScoreRank.getValue()));
        unionYRank.setParam((score) + "=" + warType + "#" + ability);
        unionYRank.setUpdateTime(time);
        unionYRank.setUnionBaseInfo(unionJoin == null ? null : unionJoin.getUnionBaseInfo());
        if (unionYRank.getPosMap() == null || unionYRank.getPosMap().isEmpty()) {
            ConcurrentHashMap<Long, Integer> memberMap = new ConcurrentHashMap<>();
            for (CrossSuiTangUnionJoinMember member : unionJoin.getMemberMap().values()) {
                memberMap.put(member.getUserId(), member.getPosition());
            }
            unionYRank.setPosMap(memberMap);
        }
        CrossYRankMgr.unionRankChange(unionYRank.getActivityId(), unionYRank.getGroupId(), unionYRank.getIdKey(), unionYRank.getUnionUid(),
                unionYRank.getUnionBaseInfo(), unionYRank.getPosMap(), UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, time, unionYRank.getParam());
    }

    /*
     * 重置战场内各个组的商会势力排行
     */
    public void resetWarUnionRank() {
        for (Map<Integer, CrossSuiTangRankListModel> rankListModelMap : activity.getWarUnionRankMap().values()) {
            rankListModelMap.clear();
        }
        initWarUnionRank();
    }

    /*
     * 更新战场内各个组的商会势力排行
     */
    public void updateWarUnionRank(String unionId, long score, long time) {
        CrossSuiTangUnionJoinData unionJoin = getUnionJoin(unionId);
        CrossSuiTangUnionData unionData = getUnionData(unionId);
        // v6.9 改为赚钱
        long ability = unionJoin == null ? 0 : unionJoin.getUnionBaseInfo().getTotalPatronsAbility().longValue();
        Map<eSuiTangWarType, Map<Integer, CrossSuiTangRankListModel>> warUnionRankMap = activity.getWarUnionRankMap();
        if (warUnionRankMap.isEmpty()) {
            warUnionRankMap.put(eSuiTangWarType.WAR_TYPE_YIJUN, new ConcurrentHashMap<>());
            warUnionRankMap.put(eSuiTangWarType.WAR_TYPE_XIAOQI, new ConcurrentHashMap<>());
            warUnionRankMap.put(eSuiTangWarType.WAR_TYPE_JINJUN, new ConcurrentHashMap<>());
        }
        Map<Integer, CrossSuiTangUnionRound> unionRoundMap = unionData.getUnionRoundMap();
        if (unionRoundMap == null || unionRoundMap.isEmpty()) {
            return;
        }
        CrossSuiTangUnionRound unionRound = unionRoundMap.get(calcRound());
        if (unionRound == null) {
            return;
        }
        CrossSuiTangRankListModel rank = warUnionRankMap.get(unionRound.getWarType()).get(unionRound.getActGroupId());
        if (rank == null) {
            rank = new CrossSuiTangRankListModel();
            warUnionRankMap.get(unionRound.getWarType()).put(unionRound.getActGroupId(), rank);
        }
//        CrossSuiTangRank myRankInfo = rank.getMyRankInfo(unionId);
//        long scoreTemp = myRankInfo == null ? score : Math.max(myRankInfo.getValue() + score, 0);
        rank.rankChange(new CrossSuiTangRank(unionId, score, ability, time));

        // 更新下商会排行积分
        updateUnionRank(unionRound.getWarType(), unionRound.getActGroupId());
    }

    /*
     * 初始化战场内排行榜
     */
    public void initWarUnionRank() {
        for (CrossSuiTangUnionJoinData join : activity.getUnionJoinDataMap().values()) {
            CrossSuiTangUnionRound unionRoundData = getUnionRoundData(join.getUnionUid());
            SuiTangCityTypeConfig suiTangCityTypeConfig = activity.getConfig().getCityTypeConfigMap().get(activity.getConfig().getCityTypeConfigKey(unionRoundData.getWarType(), eSuiTangCityType.CITY_TYPE_HOME.getType()));
            if (suiTangCityTypeConfig == null) {
                return;
            }
            // 初始化战场内榜单
            initWarUnionRank(join.getUnionUid(), suiTangCityTypeConfig.getCampPoint(calcRound() - 1), System.currentTimeMillis());
        }
    }

    /*
     * 初始化战场内排行榜
     */
    public void initWarUnionRank(String unionId, long score, long time) {
        CrossSuiTangUnionJoinData unionJoin = getUnionJoin(unionId);
        CrossSuiTangUnionData unionData = getUnionData(unionId);
        if (unionData == null) {
            // 初始化商会活动数据
            activity.getUnionActivityMgr().initUnionData();
            unionData = getUnionData(unionId);
        }
        // v6.9 改为赚钱
        long ability = unionJoin == null ? 0 : unionJoin.getUnionBaseInfo().getTotalPatronsAbility().longValue();
        Map<eSuiTangWarType, Map<Integer, CrossSuiTangRankListModel>> warUnionRankMap = activity.getWarUnionRankMap();
        if (warUnionRankMap.isEmpty()) {
            warUnionRankMap.put(eSuiTangWarType.WAR_TYPE_YIJUN, new ConcurrentHashMap<>());
            warUnionRankMap.put(eSuiTangWarType.WAR_TYPE_XIAOQI, new ConcurrentHashMap<>());
            warUnionRankMap.put(eSuiTangWarType.WAR_TYPE_JINJUN, new ConcurrentHashMap<>());
        }
        Map<Integer, CrossSuiTangUnionRound> unionRoundMap = unionData.getUnionRoundMap();
        if (unionRoundMap == null || unionRoundMap.isEmpty()) {
            return;
        }
        CrossSuiTangUnionRound unionRound = unionRoundMap.get(calcRound());
        if (unionRound == null) {
            return;
        }
        CrossSuiTangRankListModel rank = warUnionRankMap.get(unionRound.getWarType()).get(unionRound.getActGroupId());
        if (rank == null) {
            rank = new CrossSuiTangRankListModel();
            warUnionRankMap.get(unionRound.getWarType()).put(unionRound.getActGroupId(), rank);
        }
        CrossSuiTangRank myRankInfo = rank.getMyRankInfo(unionId);
        long scoreTemp = myRankInfo == null ? score : Math.max(myRankInfo.getValue() + score, 0);
        rank.rankChange(new CrossSuiTangRank(unionId, scoreTemp, ability, time));
    }

    /*
     * 结算
     */
    public void settle(eSuiTangStage step) {
        logger.debug("结算：{}", step);
        activity.getCityActivityMgr().mailSendCityCollect();
        updateUnionRank();
        resetInfo();
    }

    /*
     * 22点重置
     */
    public void resetInfo() {
        // 重置疲敝状态
        for (CrossSuiTangUserData userData : activity.getUserDataMap().values()) {
            CrossSuiTangTeam team = userData.getTeam();
            if (team != null) {
                team.setCurBattleNum(0);
            }
        }
    }

    /*
     * 更新商会积分榜单
     */
    public void updateUnionRank() {
        for (Map.Entry<eSuiTangWarType, Map<Integer, CrossSuiTangRankListModel>> entry : activity.getWarUnionRankMap().entrySet()) {
            eSuiTangWarType warType = entry.getKey();
            Map<Integer, CrossSuiTangRankListModel> actGroupMap = entry.getValue();
            for (Map.Entry<Integer, CrossSuiTangRankListModel> modelEntry : actGroupMap.entrySet()) {
                int actGroupId = modelEntry.getKey();
                updateUnionRank(warType, actGroupId);
            }
        }
    }

    /*
     * 更新商会积分榜单
     */
    public void updateUnionRank(eSuiTangWarType warType, int actGroupId) {
        Map<Integer, CrossSuiTangRankListModel> warUnionRankMap = activity.getWarUnionRankMap().get(warType);
        if (warUnionRankMap == null) {
            return;
        }
        CrossSuiTangRankListModel model = warUnionRankMap.get(actGroupId);
        if (model == null) {
            return;
        }
        for (CrossSuiTangRank rank : model.getRankList()) {
            int index = model.getMyRank(rank.getId());
            int rankScore = 0;
            CrossSuiTangUnionJoinData unionJoin = getUnionJoin(rank.getId());
            if (unionJoin == null) {
                continue;
            }
            for (int round = 1; round <= 3; round++) {
                CrossSuiTangUnionRound unionRoundData = getUnionRoundData(rank.getId(), round);
                if (unionRoundData == null) {
                    continue;
                }
                if (calcRound() == round) {
                    unionRoundData.setRank(index);
                }
                rankScore += activity.getConfig().getRankScore(round, unionRoundData.getWarType().getType(), unionRoundData.getRank());
                //势力积分按比例转换为榜单积分
                rankScore +=  activity.getConfig().getCityScoreToRankScore(round, unionRoundData.getWarType().getType(), unionRoundData.getCurrentCityScore().get());
            }
            if (rankScore == 0) {
                continue;
            }
            CrossSuiTangUnionData unionData = getUnionData(rank.getId());
            if (unionData != null) {
                unionData.setTotalScore(Math.max(rankScore, 0));
                unionData.setUpdateOption();
            }
            updateUnionRank(rank.getId(), rankScore, unionJoin.getUnionBaseInfo().getUnionAliasId());
        }
    }
    /*
     * 获取个人军功排行
     */
    public int GetUserRankInUnion(long userId) {
        CrossSuiTangUserData userData = activity.getUserData(userId);
        List<UserYRank> list = CrossYRankMgr.getSortUnionContributionList(activity.getConfig().getActivityId(), activity.getGroupId(),
                String.valueOf(eGamePlayerEventType.SuiTangUnionScoreRank.getValue()),
                String.valueOf(eGamePlayerEventType.SuiTangUserZhanGongRank.getValue()),
                userData.getUnionUid());
        return CrossYRankMgr.getUserRankNum(list, userId);
    }
}
